<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";
import { sendSMS } from "@/utils/api";
import { certificate, membersinfo, membersDetail,recognizeIdCard } from "@/utils/api";
import { baseURL } from "@/utils/request";
import { baseimgURL } from '@/config'
// 表单数据
const formData = reactive({
  certificateName: "",
  certificateCardNumber: "",
  mobile: "",
});
const formData2 = reactive({
  certificateName: "",
  certificateCardNumber: "",

});
const renzhengid=ref(null)
// 页面加载
onLoad(async (options) => {
  if (options.id) {
    const { data } = await membersDetail({ id: options.id });
    let dataobj=data.memberCertificate
    checked.value = data.memberCertificate.certificateType;
    renzhengid.value= Number(JSON.parse(uni.getStorageSync("userinfo")).memberCertificate.id)
    if (data.memberCertificate.certificateType == 1) {
      Object.keys(formData).forEach((key) => (formData[key] = dataobj[key]));  
        formData.mobile=data.mobile
      // 处理回显的图片
      let arrimg = data.memberCertificate? data.memberCertificate.certificatePhoto.split(","):'';
      if (arrimg && arrimg.length > 0) {
        fileList1.value = [
          {
            url: `${baseimgURL}${arrimg[0]}`,
          },
        ];
        fileList2.value = [
          {
            url: `${baseimgURL}${arrimg[1]}`,
          },
        ];
      }

      formData.certificatePhoto;
    } else {
      Object.keys(formData2).forEach((key) => (formData2[key] = data.memberCertificate[key]));
      formData.mobile=data.mobile
      let arrimg = data.memberCertificate? data.memberCertificate.certificatePhoto.split(","):'';
      if (arrimg && arrimg.length > 0) {
        fileList3.value = [
          {
            url: `${baseimgURL}${arrimg[0]}`,
          },
        ];
      }
    }
  } else {
    formData.mobile = JSON.parse(uni.getStorageSync("userinfo")).mobile;
  }
});

const rules = {
  certificateName: {
    type: "string",
    required: true,
    message: "请输入姓名",
    trigger: ["blur"],
  },
  certificateCardNumber: {
    type: "string",
    required: true,
    message: "请输入",
    trigger: ["blur"],
  },
};
const checked = ref(1);
const uForm = ref();
const fileList1 = ref([]);
const fileList2 = ref([]);
const fileList3 = ref([]);
const submit = () => {
  let param = {};
  uForm.value.validate().then((res) => {
    if (checked.value == 1) {
      if (
        fileList1 &&
        fileList2 &&
        fileList1.value.length > 0 &&
        fileList2.value.length > 0
      ) {
        let arrfile = [].concat(fileList1.value[0].url.replace(`${baseimgURL}/`, '/'), fileList2.value[0].url.replace(`${baseimgURL}/`, '/'));
        const arrfilestr = arrfile.join(",");
        console.log(arrfilestr);
        param = {
          phoneNum: formData.mobile,
          certificateType: checked.value,
          certificatePhoto: arrfilestr,
          certificateCardNumber: formData.certificateCardNumber,
          certificateName: formData.certificateName,
          verifyCode: formData.verifyCode,
        };
        if(renzhengid.value){
          param.id=renzhengid.value
        }
      } else {
        uni.showToast({ icon: "none", title: "请上传完整证件" });
        return;
      }
    } else {
      if(fileList3&&fileList3.value.length>0){
        param = {
        phoneNum: formData.mobile,
        certificateType: checked.value,
        certificatePhoto: fileList3.value[0].url.replace(`${baseimgURL}/`, '/'),
        certificateCardNumber: formData2.certificateCardNumber,
        certificateName: formData2.certificateName,
        verifyCode: formData2.verifyCode,
      };
      if(renzhengid.value){
          param.id=renzhengid.value
        }
      }else{
        uni.showToast({ icon: "none", title: "请上传完整证件" });
        return;
      }
 
    }

    certificate(param).then((res) => {
      uni.$u.toast("提交成功");
      // 更新实名认证状态
      membersinfo().then((meinfo) => {
        uni.setStorageSync("userinfo", JSON.stringify(meinfo.data));
        uni.redirectTo({
          url: `/pages/me/authenticationresult?status=${meinfo.data.memberCertificate.auditStatus}`,
        });
      });
    });
  });
};

// 删除图片
const deletePic = (event, list) => {
  list.splice(event.index, 1);
};

// 新增图片识别第一个
const afterReadocr = async (event, list, type) => {
 
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);

  let fileListLen = list.length;
  lists.map((item) => {
    console.log(list);
    list.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url);

    const resulturl = JSON.parse(result).data.url;
    let paramurl=`${baseimgURL}${resulturl}`

    const IdCardresult = await uploadFilePromiseOCR(lists[i].url,paramurl,type);
    if(JSON.parse(IdCardresult).code==1){
   let IdCardresultData=JSON.parse(IdCardresult).data
   if(type=='营业执照'){
    formData2.certificateName=IdCardresultData.companyName
    formData2.certificateCardNumber=IdCardresultData.creditCode
   }else{
    formData.certificateName=IdCardresultData.name
   formData.certificateCardNumber=IdCardresultData.idNumber
   }

    }else{
      if(type=='营业执照'){
    formData2.certificateName=''
    formData2.certificateCardNumber=''
   }else{
    formData.certificateName=''
   formData.certificateCardNumber=''
   }
      uni.showToast({
						title: `${type}识别失败`,
						icon: 'none'
					})
    }

    // const result = "https://cdn.uviewui.com/uview/demo/upload/positive.png";
    let item = list[fileListLen];
    list.splice(fileListLen, 1, {
      ...item,
      status: "success",
      message: "",
      // url: resulturl,
      url: `${baseimgURL}${resulturl}`,
    });
    fileListLen++;
  }
};
// 新增图片
const afterRead = async (event, list) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);

  let fileListLen = list.length;
  lists.map((item) => {
    console.log(list);
    list.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url);
    const resulturl = JSON.parse(result).data.url;
    // const result = "https://cdn.uviewui.com/uview/demo/upload/positive.png";
    let item = list[fileListLen];
    list.splice(fileListLen, 1, {
      ...item,
      status: "success",
      message: "",
      // url: resulturl,
      url: `${baseimgURL}${resulturl}`,
    });
    fileListLen++;
  }
};

const uploadFilePromiseOCR = (url,paramurl,type) => {
  const token = uni.getStorageSync("token");
  const token_type = uni.getStorageSync("token_type");
  // upload.headers['Authorization'] =`${token_type} ` + `${token}`
  return new Promise((resolve, reject) => {
    let b= uni.uploadFile({
      url: type=='营业执照'?`${baseURL}/zgyp-system/api/v1/files/recognizeBusiness`:`${baseURL}/zgyp-system/api/v1/files/recognizeIdCard`, 
      filePath: url,
      name: "file",
      header: {
        "content-type": "multipart/form-data",
        Authorization: `${token_type} ` + `${token}`,
      },
      formData: {
			url: paramurl, 
      file:''
      },
      success: (res) => {
        resolve(res.data);
      },catch:(err)=>{
console.log(err)
      }
    });
  });
};
const uploadFilePromise = (url) => {
  const token = uni.getStorageSync("token");
  const token_type = uni.getStorageSync("token_type");
  // upload.headers['Authorization'] =`${token_type} ` + `${token}`
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: `${baseURL}/zgyp-system/api/v1/files`, 
      filePath: url,
      name: "file",
      header: {
        "content-type": "application/json",
        Authorization: `${token_type} ` + `${token}`,
      },
      formData: {
			typeCode: 'certificate', //功能编码
			fieldProperty: 'certificatePhoto', //字段属性名
      },
      success: (res) => {
        resolve(res.data);
      },
    });
  });
};
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
const uCodeRef = ref(null);
// 获取验证码'
const mobileFocus = ref(false);
const tips = ref("获取验证码");
const codeChange = (text) => {
  tips.value = text;
};
const getCode = async () => {
  if (formData.mobile && /^1\d{10}$/.test(formData.mobile)) {
    if (uCodeRef.value.canGetCode) {
      uni.showLoading({
        title: "正在获取验证码",
      });
      try {
        let params = {
          mobile: formData.mobile,
          type: 6,
        };
        console.log(formData.mobile);
        // 需要对接后端获取验证码 不然会报错
        const { data } = await sendSMS(params);
        uni.hideLoading();
        uni.$u.toast("验证码已发送");
        // 通知验证码组件内部开始倒计时
        uCodeRef.value.start();
      } catch (e) {
        console.error(e);
      }
    } else {
      mobileFocus.value = false;
      uni.$u.toast("倒计时结束后再发送");
    }
  } else {
    uni.$u.toast("请输入正确的手机号码");
    mobileFocus.value = true;
  }
};
</script>

<template>
  <view>
    <view class="flex tabbox">
      <image
        v-if="checked == 1"
        class="checkleft"
        mode="widthFix"
        src="@/static/img/checkleft.png"
      ></image>
      <image
        v-if="checked == 2"
        class="checkright"
        mode="widthFix"
        src="@/static/img/checkright.png"
      ></image>
      <view class="tabitem" @tap="checked = 1">个人认证</view>
      <view class="tabitem" @tap="checked = 2">企业认证</view>
    </view>
    <view class="content">
      <view v-if="checked == 1">
        <view class="title">上传身份证照片</view>
        <view class="huitip">身份证照片仅用于实名认证，平台不会留存您的信息</view>
      </view>
      <view v-if="checked == 2">
        <view class="title">上传营业执照</view>
        <view class="huitip">营业执照仅用于实名认证，平台不会留存您的信息</view>
      </view>
 
 
      <u--form
        v-if="checked == 1"
        :model="formData"
        :rules="rules"
        ref="uForm"
        labelWidth="160"
      >
        <view class="formbox">
          <view class="flex">
            <view class="sfzbox">
              <u-upload
                :fileList="fileList1"
                @afterRead="afterReadocr($event, fileList1,'身份证')"
                @delete="deletePic($event, fileList1)"
                name="1"
                :maxCount="1"
                width="300"
                height="200"
              >
                <image
                  class="sfzimg"
                  mode="widthFix"
                  src="@/static/img/idCard1.png"
                ></image>
              </u-upload>
            </view>
            <view class="sfzbox">
              <u-upload
                :fileList="fileList2"
                @afterRead="afterRead($event, fileList2)"
                @delete="deletePic($event, fileList2)"
                name="2"
                :maxCount="1"
                width="300"
                height="200"
              >
                <image
                  class="sfzimg"
                  mode="widthFix"
                  src="@/static/img/idCard2.png"
                ></image>
              </u-upload>
            </view>
          </view>
          <u-form-item
            label="真实姓名 *"
            prop="certificateName"
            :borderBottom="true"
          >
                 
            <u--input
              border="none"
              disabled
              disabledColor="#FFFFFF"
              placeholder="自动识别真实姓名"
              clearable
              v-model="formData.certificateName"
            />
          </u-form-item>
          <u-form-item
            label="身份证号 *"
            prop="certificateCardNumber"
            :borderBottom="true"
          >
            <u--input
              border="none"
              disabled
              disabledColor="#FFFFFF"
              placeholder="自动识别身份证号码"
              clearable
              v-model="formData.certificateCardNumber"
            />
          </u-form-item>
          <u-form-item label="手机号 *" prop="mobile" :borderBottom="true">
            <u--input
              border="none"
              clearable
              disabled
              disabledColor="#FFFFFF"
              v-model="formData.mobile"
            />
          </u-form-item>
          <u-form-item label="验证码" prop="verifyCode" :borderBottom="true">
            <u-input
              v-model="formData.verifyCode"
              placeholder="请输入验证码"
              border="none"
            />
            <template #right>
              <u-code
                ref="uCodeRef"
                @change="codeChange"
                seconds="60"
                changeText="X秒重新获取"
              ></u-code>
              <!-- <template #right> 获取验证码 </template> -->
              <text @tap="getCode" class="yanzm">{{ tips }}</text>
            </template>
          </u-form-item>
        </view>
      </u--form>
      <u--form
        v-if="checked == 2"
        :model="formData2"
        :rules="rules"
        ref="uForm"
        labelWidth="160"
      >
        <view class="formbox">
          <view class="flex_1">
            <view class="sfzbox">
              <u-upload
                :fileList="fileList3"
                @afterRead="afterReadocr($event, fileList3,'营业执照')"
                @delete="deletePic($event, fileList3)"
                name="2"
                :maxCount="1"
                width="300"
                height="200"
              >
                <image
                  class="sfzimg"
                  mode="widthFix"
                  src="@/static/img/zhizhao.png"
                ></image>
              </u-upload>
            </view>
          </view>
          <u-form-item label="企业名称" prop="name" :borderBottom="true">
            <u--input
              border="none"
              disabled
              disabledColor="#FFFFFF"
              clearable
              v-model="formData2.certificateName"
              placeholder="自动识别企业名称"
            />
          </u-form-item>
          <u-form-item label="信用代码" prop="idcard" :borderBottom="true">
            <u--input
              border="none"
              disabled
              disabledColor="#FFFFFF"
              placeholder="自动识别信用代码"
              clearable
              v-model="formData2.certificateCardNumber"
            />
          </u-form-item>
          <u-form-item label="手机号 *" prop="mobile" :borderBottom="true">
            <u--input
              border="none"
              clearable
              disabled
              disabledColor="#FFFFFF"
              v-model="formData.mobile"
              :focus="mobileFocus"
            />
          </u-form-item>
          <u-form-item label="验证码" prop="verifyCode" :borderBottom="true">
            <u-input
              v-model="formData2.verifyCode"
              placeholder="请输入验证码"
              border="none"
            />
            <template #right>
              <u-code
                ref="uCodeRef"
                @change="codeChange"
                seconds="60"
                changeText="X秒重新获取"
              ></u-code>
              <!-- <template #right> 获取验证码 </template> -->
              <text @tap="getCode" class="yanzm">{{ tips }}</text>
            </template>
          </u-form-item>
        </view>
      </u--form>

      <!-- 吸底工具栏 -->
      <view
        class="toolbar-height"
        :style="{ paddingBottom: safeAreaInsets?.bottom + 30 + 'px' }"
      ></view>
      <view
        class="toolbar"
        :style="{ paddingBottom: safeAreaInsets?.bottom + 30 + 'px' }"
      >
        <view class="button-grounp">
          <view @tap="submit" class="button payment-button"> 提交认证 </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #ffffff;
}
.content {
  padding: 26rpx 32rpx;
  .title {
    font-size: 28rpx;
    font-weight: 500;
  }
  .formbox {
    background: #fff;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
  }
}
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 2;
  height: 100rpx;
  padding: 14rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  box-sizing: content-box;
  .button-grounp {
    display: flex;
    justify-content: center;
    text-align: center;
    line-height: 72rpx;
    font-size: 13px;
    color: #fff;

    .button {
      width: 490rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
    }

    .payment-button {
      background: #953b82;
      border-radius: 8rpx;
      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
.toolbar-height {
  height: 100rpx;
  box-sizing: content-box;
}
.huitip {
  font-size: 26rpx;
  color: #999999;
  margin-top: 12rpx;
  margin-bottom: 32rpx;
}
.tips {
  text-align: center;
  font-size: 26rpx;
  font-weight: 400;
  color: #79a9ff;
  margin-top: 18rpx;
}
.sfzbox {
  margin-bottom: 20rpx;
  flex: 1;
  text-align: center;
}
/* h5 需要加::v-deep */
::v-deep .u-upload__wrap {
  justify-content: center;
}

.sfzimg {
  width: 320rpx;
  height: 220rpx;
}
.tabbox {
  position: relative;
  height: 82rpx;
  line-height: 82rpx;
  background: linear-gradient(180deg, #f4f4f4 0%, #ffffff 100%);
  border-radius: 14px 0px 0px 0px;
  border: 2px solid #ffffff;
  text-align: center;
  box-sizing: border-box;
}
.tabitem {
  flex: 1;
  line-height: 82rpx;
  position: relative;
  z-index: 3;
  text-align: center;
}
.checkleft {
  position: absolute;
  left: 0;
  top: -2rpx;
  width: 387rpx;
  height: 82rpx;
  z-index: 2;
}
.checkright {
  position: absolute;
  right: 0;
  top: -2rpx;
  width: 387rpx;
  height: 82rpx;
  z-index: 2;
}
</style>
